package com.hhkj.admin.question.common.converter;

import cn.hutool.core.collection.CollectionUtil;
import com.hhkj.admin.question.model.req.QuestionReq;
import com.hhkj.admin.question.model.res.QuestionRes;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * QuestionListConverter
 *
 * @author ZhengJun
 * @since 2023/5/27 20:55
 */
public class QuestionCollectionConverter
{

    /**
     * listGroup转为list
     *
     * @param questionGroupList 题目组列表
     * @return 题目组列表信息
     */
    public static List<QuestionReq> groupReqToList(List<QuestionReq> questionGroupList)
    {
        List<QuestionReq> questionList = new ArrayList<>();
        for (QuestionReq questionGroup : questionGroupList) {
            questionList.add(questionGroup);
            if (CollectionUtil.isNotEmpty(questionGroup.getQuestionList())) {
                questionList.addAll(questionGroup.getQuestionList());
            }
        }
        return questionList;
    }

    /**
     * 处理题目列表信息，进行题目组分组
     *
     * @param questionList 题目列表
     * @return 题目列表
     */
    public static List<QuestionRes> listToListGroup(List<QuestionRes> questionList)
    {
        Map<Long, List<QuestionRes>> questionListGroupByParentId = questionList.stream()
                .collect(Collectors.groupingBy(QuestionRes::getParentId));
        List<QuestionRes> questionGroupList
                = questionListGroupByParentId.getOrDefault(0L, new ArrayList<>());
        for (QuestionRes questionGroup : questionGroupList) {
            if (questionListGroupByParentId.containsKey(questionGroup.getId())) {
                questionGroup.setQuestionList(questionListGroupByParentId.get(questionGroup.getId()));
            }
        }
        return questionGroupList;
    }

}
